package graph

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"

	"github.com/sirupsen/logrus"
	"github.com/xuelang-group/suanpan-appconnector/pkg/common"
)

type EnvItem struct {
	Name  string      `json:"name"`
	Value interface{} `json:"value,string"`
}

type ConnctApiResponseData struct {
	Success bool `json:"success"`
	Data    struct {
		DownloadLists []common.DownloadList `json:"downloadList"`
		UploadLists   []common.UploadList   `json:"uploadList"`
		WatchLists    []common.WatchList    `json:"watchList"`
		Cmd           string                `json:"cmd"`
		Env           []EnvItem             `json:"env"`
	} `json:"data"`
	Msg string `json:"msg"`
}

func NewConnectApiResponseData() *ConnctApiResponseData {
	return &ConnctApiResponseData{
		Success: true,
		Msg:     "empty",
	}
}

type HttpConnectApiResult struct {
	response *http.Response
	err      error
}

func HttpResultToApiResponseData(res HttpConnectApiResult) *ConnctApiResponseData {
	if res.err != nil {
		logrus.Errorf("http client request exception %s", res.err.Error())
		return nil
	}
	var ret ConnctApiResponseData
	body, err := ioutil.ReadAll(res.response.Body)
	logrus.Debugf("api data from remote raw, data:%v", string(body))
	if err == nil {
		if err = json.Unmarshal(body, &ret); err == nil {
			if ret.Success {
				return &ret
			} else {
				logrus.Errorf("remote api return failed: %s", ret.Msg)
				return nil
			}
		} else {
			logrus.Errorf("json unmashal failed %s", err.Error())
			return nil
		}
	} else {
		logrus.Errorf("http response io read failed %s", err.Error())
		return nil
	}
}

func HttpRequestGetAsync(url string) chan HttpConnectApiResult {
	res := make(chan HttpConnectApiResult)

	go func(url string) {
		response, err := http.Get(url)
		if err != nil {
			res <- HttpConnectApiResult{response: nil, err: err}
		} else {
			res <- HttpConnectApiResult{response: response, err: nil}
		}
	}(url)

	return res
}

func GetGraphInfo() *ConnctApiResponseData {
	requestUrl := fmt.Sprintf("%s/connect/%s/%s/%s",
		common.GetApiServer(), common.GetUserId(), common.GetAppId(), common.GetNodeId())
	logrus.Debugf("request api to get graph, %s", requestUrl)
	result := <-HttpRequestGetAsync(requestUrl)
	apiData := HttpResultToApiResponseData(result)
	return apiData
}

func (a *ConnctApiResponseData) GetSpDebugMode() string {
	ret := ""
	for _, env := range a.Data.Env {
		if env.Name == "SP_DEBUG" {
			val, ok := env.Value.(string)
			if ok {
				ret = val
				break
			}
		}
	}

	return ret
}
